//
//  JKMyCollectionViewController.swift
//  ZhiHuDaily-Swift
//
//  Created by albert on 2018/3/13.
//  Copyright © 2018年 安永博. All rights reserved.
//

import UIKit

class JKMyCollectionViewController: JKBaseViewController {
    
    /** 模型数组 */
    private lazy var stories: [JKNewsListModel] = [JKNewsListModel]()
    
    public lazy var noCollectionImgView: UIImageView = {
        
        let imgView = UIImageView()
        
        imgView.image = UIImage(named: "Menu_Icon_Collect")
        view.insertSubview(imgView, belowSubview: contentView)
        
        imgView.frame = CGRectMake((JKScreenW - 30) * 0.5, 180, 30, 30)
        
        return imgView
    }()
    
    public lazy var noCollectionLabel: UILabel = {
        
        let lb = UILabel()
        
        lb.text = "还没有收藏内容"
        lb.textColor = JKColor(168, 168, 168)
        lb.font = UIFont.systemFont(ofSize: 14)
        lb.sizeToFit()
        lb.width = JKScreenW
        lb.textAlignment = NSTextAlignment.center
        
        lb.centerX = self.noCollectionImgView.centerX
        lb.y = self.noCollectionImgView.y + 30 + 15
        view.insertSubview(lb, belowSubview: contentView)
        
        return lb
    }()
    
    public lazy var cancelButton: UIButton = {
        
        let button = UIButton(type: UIButtonType.custom)
        button.titleLabel?.font = navBackButton.titleLabel?.font
        button.setTitle("取消", for: UIControlState.normal)
        button.setTitleColor(UIColor.gray, for: UIControlState.highlighted)
        button.setTitleColor(UIColor.lightGray, for: UIControlState.disabled)
        button.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
        
        button.addTarget(self, action: #selector(exitEditingModel), for: UIControlEvents.touchUpInside)
        
        return button
    }()
    
    public lazy var editButton: UIButton = {
        
        let button = UIButton(type: UIButtonType.custom)
        button.titleLabel?.font = navBackButton.titleLabel?.font
        button.setTitle("编辑", for: UIControlState.normal)
        button.setTitleColor(UIColor.gray, for: UIControlState.highlighted)
        button.setTitleColor(UIColor.lightGray, for: UIControlState.disabled)
        button.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
        
        button.addTarget(self, action: #selector(editButtonClick), for: UIControlEvents.touchUpInside)
        
        return button
    }()
    
    // MARK:- 生命周期方法
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        navigationController?.setNavigationBarHidden(false, animated: true)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        
        
    }
    
    // MARK: - 初始化

    override func viewDidLoad() {
        super.viewDidLoad()

        navTitle = "收藏"
        
        contentView.backgroundColor = view.backgroundColor
        
        let _ = noCollectionLabel
    }
    
    override func setupNav() {
        
        let _ = editButton
    }
    
    /** 初始化tableView */
    internal override func setupTableView() {
        
        tableViewPlain.rowHeight = 80
        tableViewPlain.showsVerticalScrollIndicator = true
        
        tableViewPlain.contentInset = UIEdgeInsets(top: JKNavBarHeight, left: 0, bottom: JKCurrentHomeIndicatorHeight, right: 0)
        
        if #available(iOS 11.0, *) {
            
        } else {
            
            tableViewPlain.scrollIndicatorInsets = tableViewPlain.contentInset
        }
        
        tableViewPlain.contentOffset = CGPoint(x: 0, y: -tableViewPlain.contentInset.top)
        
        tableViewPlain.register(UINib(nibName: "JKNewsListCell", bundle: nil), forCellReuseIdentifier: "JKNewsListCell")
        
        let tipLabel = UILabel(frame: CGRectMake(0, 0, JKScreenW, 44))
        tipLabel.text = "本地收藏"
        tipLabel.textAlignment = NSTextAlignment.center
        tipLabel.font = UIFont.systemFont(ofSize: 12)
        tipLabel.textColor = JKSameRGBColor(168)
        tableViewPlain.tableFooterView = tipLabel
    }
    
    // MARK: - 加载数据
    
    override func loadNewData() {
        
        let stories = JKSQLiteManager.queryCollectedStoryList()
        
        guard let newsListModels = [JKNewsListModel].deserialize(from: stories) else {
            
            contentView.isHidden = true
            editButton.isHidden = true
            
            return
        }
        
        self.stories = newsListModels as! [JKNewsListModel]
        
        if stories.count < 1 {
            
            contentView.isHidden = true
            editButton.isHidden = true
            
            return
        }
        
        contentView.isHidden = false
        editButton.isHidden = false
        
        tableViewPlain.reloadData()
    }
    
    // MARK: - 点击事件
    
    override func navBackButtonClick() {
        
        let mainNav = navigationController as! JKMainNavigationController
        
        if mainNav.showLeftVcBlock != nil {
            
            mainNav.showLeftVcBlock!()
        }
    }
    
    @objc func editButtonClick(button: UIButton) {
        
        if button.currentTitle == "编辑" {
            
            enterEditingModel()
            
            return
        }
        
        if button.currentTitle == "删除" {
            
            deleSelectStories()
            
            return
        }
    }
    
    /** 批量删除 */
    private func deleSelectStories() {
        
        // 获得所有被选中的行
        guard let indexPaths = tableViewPlain.indexPathsForSelectedRows else {
            
            return
        }
        
        // 遍历所有的行号
        var deletedStories = [JKNewsListModel]()
        var deletedStoryIDs = [String]()
        
        var rows = [Int]()
        
        for indexPath in indexPaths {
            
            let model = stories[indexPath.row]
            
            deletedStories.append(model)
            deletedStoryIDs.append(model.id!)
            
            rows.append(indexPath.row)
        }
        
        // 更新为未收藏状态
        JKSQLiteManager.updateCollectionsCancelWithStoryIDs(storyIDs: deletedStoryIDs)
        
        let sortedRows = rows.sorted { (num1, num2) -> Bool in
            
            return num1 > num2
        }
        
        // 删除模型数据
        for i in sortedRows {
            
            stories.remove(at: i)
        }
        
        tableViewPlain.deleteRows(at: indexPaths, with: UITableViewRowAnimation.automatic)
        
        // 最后再退出编辑模式
        exitEditingModel()
    }
    
    /** 进入编辑模式 */
    private func enterEditingModel() {
        
        editButton.setTitle("删除", for: UIControlState.normal)
        editButton.setTitleColor(UIColor.red, for: UIControlState.normal)
        editButton.isEnabled = false
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: cancelButton)
        
        tableViewPlain.reloadSections(IndexSet.init(integer: 0), with: UITableViewRowAnimation.automatic)
        
        // 允许在编辑模式进行多选操作
        tableViewPlain.allowsMultipleSelectionDuringEditing = true
        tableViewPlain.setEditing(true, animated: true)
    }
    
    /** 退出编辑模式 */
    @objc private func exitEditingModel() {
        
        editButton.isEnabled = true
        
        tableViewPlain.setEditing(false, animated: true)
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: navBackButton)
        
        editButton.setTitle("编辑", for: UIControlState.normal)
        editButton.setTitleColor(UIColor.white, for: UIControlState.normal)
        
        if (self.stories.count == 0) {
            
            contentView.isHidden = true
            editButton.isHidden = true
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

// MARK: - tableView dataSource

extension JKMyCollectionViewController {
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return stories.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var cell = tableView.dequeueReusableCell(withIdentifier: "JKNewsListCell") as? JKNewsListCell
        
        if (cell == nil) {
            
            cell = JKNewsListCell(style: UITableViewCellStyle.default, reuseIdentifier: "JKNewsListCell")
        }
        
        let model = stories[indexPath.row]
        
        cell?.model = model
        
        return cell!
    }
}

// MARK: - tableView delegate

extension JKMyCollectionViewController {
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if (tableView.isEditing) {
            
            self.editButton.isEnabled = true
            
            return
        }
        
        super.tableView(tableView, didSelectRowAt: indexPath)
        
        let md = stories[indexPath.row]
        
        let vc = JKNewsDetailViewController()
        
        vc.storyID = md.id
        vc.themeStories = self.stories
        vc.indexPath = indexPath
        
        navigationController?.pushViewController(vc, animated: true)
    }
    
    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        
        guard let indexPaths = tableView.indexPathsForSelectedRows else {
            
            self.editButton.isEnabled = false
            
            return
        }
        
        if indexPaths.count == 0 {
            
            self.editButton.isEnabled = false
        }
    }
    
    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        
        let action = UITableViewRowAction(style: UITableViewRowActionStyle.default, title: "取消收藏") { (action, indexP) in
            
            // 更新为未收藏状态
            let model = self.stories[indexP.row]
            let _ = JKSQLiteManager.updateCollectedStatusWithStoryID(storyID: model.id, collected: false)
            
            self.stories.remove(at: indexP.row)
            self.tableViewPlain.deleteRows(at: [indexP], with: UITableViewRowAnimation.automatic)
            
            if self.stories.count <= 0 {
                
                self.contentView.isHidden = true
                self.editButton.isHidden = true
            }
        }
        
        return [action]
    }
}

extension JKMyCollectionViewController {
    
    override func updateSkin() {
        super.updateSkin()
        
        contentView.backgroundColor = view.backgroundColor
    }
}
